<!--用例维护 add by gaojingyu-->
<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters" @submit.native.prevent>
        <el-form-item label="" label-width="83px" prop="getProjectFirstID">
          <el-select
            clearable
            v-model="filters.project_id"
            placeholder="请选择项目列表"
          >
            <el-option
              v-for="(item, index) in project"
              :key="index + ''"
              :label="item.project_name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="" label-width="83px" prop="getAPIFirstIDS">
          <el-select
            clearable
            v-model="filters.interface_id"
            placeholder="请选择测试接口"
          >
            <el-option
              v-for="(item, index) in apis"
              :key="index + ''"
              :label="item.interface_name_zh"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-input
            clearable
            v-model="filters.case_name"
            prefix-icon="el-icon-search"
            placeholder="用例名称"
            @keyup.enter.native="getLyzdCaseList"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getLyzdCaseList">查询</el-button>
        </el-form-item>

        <el-form-item>
          <router-link
            :to="{ path: 'addCase' }"
            style="text-decoration: none;color: aliceblue;"
          >
            <el-button type="primary">新增</el-button>
          </router-link>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="download">下载模板</el-button>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="upload">用例上传</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <el-dialog
      title="用例上传"
      :visible.sync="uploadform"
      :close-on-click-modal="false"
      style="width: 95%; left: 2.5%"
    >
      <el-form
        :model="editForm"
        label-width="80px"
        :rules="editFormRules"
        ref="editForm"
      >
        <el-form-item>
          <el-upload
            ref="uploadExcel"
            :action="uploadurl"
            :limit="limitNum"
            :auto-upload="false"
            accept=".xlsx"
            :before-upload="beforeUploadFile"
            :on-change="fileChange"
            :on-exceed="exceedFile"
            :on-success="handleSuccess"
            :on-error="handleError"
            :file-list="fileList"
          >
            <el-button size="small" plain>选择文件</el-button>
            <div slot="tip" class="el-upload__tip">
              只能上传xlsx(Excel2007)文件，且不超过10M
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="uploadFile"
          >立即上传</el-button
        >
        <el-button size="small" @click.native="uploadform = false"
          >取消</el-button
        >
      </div>
    </el-dialog>
    <el-dialog
      title="模板下载"
      :visible.sync="templateDownload"
      :close-on-click-modal="false"
    >
      <el-form :model="templates" label-width="120px" ref="templates">
        <el-form-item label="项目名称:">
          <el-select
            v-model="templates.project_id"
            placeholder="请选择所属项目"
            filterable
          >
            <el-option
              v-for="(item, index) in project"
              :key="index + ''"
              :label="item.project_name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="接口名称:">
          <el-select
            v-model="templates.interface_id"
            placeholder="请选择接口名称"
            filterable
          >
            <el-option
              v-for="(item, index) in apis"
              :key="index + ''"
              :label="item.interface_name_zh"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          size="small"
          type="primary"
          :plain="true"
          @click="DownloadTempla"
          >下载</el-button
        >
        <el-button
          size="small"
          @click.native="templateDownload = false"
          @click="cancelDownloadTempla"
          >取消</el-button
        >
      </div>
    </el-dialog>

    <!--列表-->
    <el-table
      :data="caselist"
      highlight-current-row
      v-loading="listLoading"
      @selection-change="selsChange"
      style="width: 100%;"
    >
      <el-table-column type="selection" min-width="5%"> </el-table-column>
      <el-table-column
        type="index"
        align="center"
        label="序号"
        :index="indexMethod"
      />
      <el-table-column prop="case_name" label="用例名称" min-width="16%">
      </el-table-column>
      <el-table-column prop="project" label=" 所属项目" min-width="16%">
      </el-table-column>
      <el-table-column prop="interface" label="测试接口" min-width="12%">
      </el-table-column>
      <el-table-column prop="case_type_name" label="用例分类" min-width="12%">
      </el-table-column>

      <el-table-column prop="status" label="状态" min-width="5%">
        <template slot-scope="scope">
          <img
            v-show="!scope.row.delete_flag"
            src="../../../../assets/icon-yes.svg"
          />
          <img
            v-show="scope.row.delete_flag"
            src="../../../../assets/icon-no.svg"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="25%">
        <template slot-scope="scope">
          <el-button
            plain
            size="small"
            type="warning"
            @click="handleResult(scope.$index, scope.row)"
            >编辑
          </el-button>

          <el-button
            plain
            type="success"
            size="small"
            @click="handleInfo(scope.$index, scope.row)"
            >详情</el-button
          >
          <el-button
            type="info"
            size="small"
            @click="handleChangeStatus(scope.$index, scope.row)"
            >{{ scope.row.delete_flag === true ? "启用" : "禁用" }}</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <!--   <el-button plain type="danger" size="small" @click="batchRemove" :disabled="this.sels.length===0">批量禁用</el-button>-->
      <el-pagination
        layout="prev, pager, next"
        @current-change="handleCurrentChange"
        :page-size="20"
        :page-count="total"
        style="float:right;"
      >
      </el-pagination>
    </el-col>
  </section>
</template>

<script>
//import NProgress from 'nprogress'
import {
  getLyzdCase,
  getApiList,
  editStatus_case,
  getApiListByProjectID,
  getProjectList,
  test,
  //addEnvironment,delEnvironment,updateEnvironment
  //, delProject, disableProject, enableProject,
} from "../../../../api/api";

// import ElRow from "element-ui/packages/row/src/row";
export default {
  // components: {ElRow},
  data() {
    return {
      filters: {
        name: "",
      },
      templates: {},
      limitNum: 1,
      project: [],
      caselist: [],
      total: 0,
      page: 1,
      listLoading: false,
      uploadurl: test + "/api/api/CaseExcleImport",
      sels: [], //列表选中列
      fileList: [],
      uploadform: false,
      // getAPIFirstID=[], //getProjectFirstID:'',
      // getAPIFirstID:'',//获取接口
      editFormVisible: false, //编辑界面是否显示
      editLoading: false,
      form: {
        getProjectFirstID: "",
        getAPIFirstIDS: "",
      },
      //options: [{ label: "Web", value: "Web"}, { label: "App", value: "App"}],

      editFormRules: {
        env_name: [
          { required: true, message: "请输入环境名称", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "长度在 1 到 50 个字符",
            trigger: "blur",
          },
        ],

        address: [
          { required: true, message: "请输入地址", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "长度在 1 到 50 个字符",
            trigger: "blur",
          },
        ],
        content: [
          { required: true, message: "请输入描述", trigger: "blur" },
          { max: 255, message: "不能超过125个字符", trigger: "blur" },
        ],
      },
      //编辑界面数据
      editForm: {
        name: "",
        version: "",
        type: "",
        description: "",
      },
      templateDownload: false,
      addFormVisible: false, //新增界面是否显示
      addLoading: false,
      addFormRules: {
        env_name: [
          { required: true, message: "请输入环境名称", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "长度在 1 到 50 个字符",
            trigger: "blur",
          },
        ],

        address: [
          { required: true, message: "请输入地址", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "长度在 1 到 50 个字符",
            trigger: "blur",
          },
        ],
        content: [
          { required: true, message: "请输入描述", trigger: "blur" },
          { max: 255, message: "不能超过125个字符", trigger: "blur" },
        ],
      },
      //新增界面数据
      addForm: {
        name: "",
        version: "",
        type: "",
        description: "",
      },
    };
  },
  methods: {
    // 获取项目列表 getLyzdEnvironments getLyzdEnvironments getLyzdCaseList  interface_id
    getLyzdCaseList() {
      this.listLoading = true;
      let self = this;
      let params = {
        page: self.page,
        interface_id: self.filters.interface_id,
        project_id: self.filters.project_id,

        case_name: self.filters.case_name,
      };

      let headers = {
        Authorization: "Token " + JSON.parse(sessionStorage.getItem("token")),
      };
      getLyzdCase(headers, params).then((res) => {
        self.listLoading = false;
        let { msg, code, data } = res;
        if (code === "999999") {
          self.total = data.total;

          var cgArr = new Array(); //常规Array

          for (var i = 0; i < data.data.length; i++) {
            if (data.data[i].case_type != 2) {
              cgArr.push(data.data[i]);
            }
          }
          self.caselist = cgArr;
        } else {
          self.$message.error({
            message: msg,
            center: true,
          });
        }
      });
    },
    indexMethod(index) {
      let curpage = this.page; //单前页码，具体看组件取值

      let limitpage = 20; //每页条数，具体是组件取值

      return index + 1 + (curpage - 1) * limitpage;
    },

    //跳转用
    handleResult: function(index, row) {
      let case_id = row.id;
      this.$router.push({ path: "/case_edit/cid=" + case_id });
    },

    handleInfo: function(index, row) {
      let case_id = row.id;
      this.$router.push({ path: "/case_info/cid=" + case_id });
    },

    getProjects() {
      let self = this;
      let params = {
        project_id: this.$route.params.project_id,
      };
      let headers = {
        "Content-Type": "application/json",
        Authorization: "Token " + JSON.parse(sessionStorage.getItem("token")),
      };
      getProjectList(headers, params).then((_data) => {
        let { msg, code, data } = _data;
        if (code === "999999") {
          var projectjsonArr = new Array();

          for (var i = 0; i < data.length; i++) {
            if (data[i].status == 0) {
              projectjsonArr.push(data[i]);
            }
          }

          self.project = projectjsonArr;
        } else {
          self.$message.error({
            message: msg,
            center: true,
          });
        }
      });
    },
    //模板下载
    download() {
      this.templateDownload = true;
    },
    //下载
    DownloadTempla() {
      let self = this;
      let param = {
        project_id: self.templates.project_id,
        interface_id: self.templates.interface_id,
      };
      if (
        self.templates.interface_id === undefined ||
        self.templates.project_id === undefined
      ) {
        this.$message("下载模板请先选择项目名称和接口名称");
      } else {
        $.ajax({
          type: "get",
          url: test + "/api/api/CaseTemplateDownload",
          async: true,
          data: param,
          headers: {
            Authorization:
              "Token " + JSON.parse(sessionStorage.getItem("token")),
          },
          timeout: 5000,
          success: function(data) {
            if (data.code === "999999") {
              self.templateDownload = false;
              self.templates.interface_id = "";
              self.templates.project_id = "";
              window.open(test + "/api/api/download_doc?url=" + data.data);
            } else {
              self.$message.error(data.msg);
            }
          },
        });
      }
    },
    //取消下载
    cancelDownloadTempla() {
      this.templates.interface_id = "";
      this.templates.project_id = "";
    },

    //文件上传
    exceedFile(files, fileList) {
      this.$notify.warning({
        title: "警告",
        message: `只能选择 ${
          this.limitNum
        } 个文件，当前共选择了 ${files.length + fileList.length} 个`,
      });
    },
    // 文件状态改变时的钩子
    fileChange(file, fileList) {
      this.form.file = file.raw;
    },
    // 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject，则停止上传
    beforeUploadFile(file) {
      let extension = file.name.substring(file.name.lastIndexOf(".") + 1);
      let size = file.size / 1024 / 1024;
      if (extension !== "xlsx") {
        this.$notify.warning({
          title: "警告",
          message: `只能上传Excel2017（即后缀是.xlsx）的文件`,
        });
      }
      if (size > 10) {
        this.$notify.warning({
          title: "警告",
          message: `文件大小不得超过10M`,
        });
      }
    },

    upload() {
      this.uploadform = true;
    },
    // 文件上传成功时的钩子
    handleSuccess(res, file, fileList) {
      if (res.code == "999999") {
        this.$notify.success({
          title: "成功",
          message: `文件上传成功`,
        });
        this.$refs.uploadExcel.clearFiles();
      } else {
        this.$confirm(res.data, res.msg, { type: "info" });
        this.$refs.uploadExcel.clearFiles();
      }
    },
    // 文件上传失败时的钩子
    handleError(err, file, fileList) {
      this.$notify.error({
        title: "错误",
        message: `文件上传失败`,
      });
    },
    uploadFile() {
      this.$refs.uploadExcel.submit();
    },
    // 改变项目状态
    handleChangeStatus: function(index, row) {
      let self = this;
      this.listLoading = true;
      let params = { case_id: row.id };

      let headers = {
        Authorization: "Token " + JSON.parse(sessionStorage.getItem("token")),
      };
      editStatus_case(headers, params).then((_data) => {
        let { msg, code, data } = _data;
        self.listLoading = false;
        if (code === "999999") {
          self.$message({
            message: msg,
            center: true,
            type: "success",
          });

          row.delete_flag = !row.delete_flag;
        } else {
          self.$message.error({
            message: msg,
            center: true,
          });
        }
      });
    },
    getAPIFirstIDS() {
      let self = this;
      let params = {
        project_id: this.$route.params.project_id,
      };
      let headers = {
        "Content-Type": "application/json",
        Authorization: "Token " + JSON.parse(sessionStorage.getItem("token")),
      };
      getApiList(headers, params).then((_data) => {
        let { msg, code, data } = _data;
        if (code === "999999") {
          var apijsonArr = new Array();

          for (var i = 0; i < data.length; i++) {
            if (data[i].delete_flag == 0) {
              apijsonArr.push(data[i]);
            }
          }

          self.apis = apijsonArr;
          //self.form.getAPIFirstID = self.apis[0].id
        } else {
          self.$message.error({
            message: msg,
            center: true,
          });
        }
      });
    },

    //删除
    handleDel: function(index, row) {
      this.$confirm("确认删除该记录吗?", "提示", {
        type: "warning",
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        let self = this;
        let params = { ids: [row.id] };
        let header = {
          "Content-Type": "application/json",
          Authorization: "Token " + JSON.parse(sessionStorage.getItem("token")),
        };
      });
    },

    handleCurrentChange(val) {
      this.page = val;
      this.getLyzdCaseList();
    },
    //显示编辑界面
    handleEdit: function(index, row) {
      this.editFormVisible = true;
      this.editForm = Object.assign({}, row);
    },
    //显示新增界面
    handleAdd: function() {
      this.addFormVisible = true;
    },
    //编辑
    editSubmit: function() {
      let self = this;
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.$confirm("确认提交吗？", "提示", {}).then(() => {
            self.editLoading = true;
            //NProgress.start();
            let params = {
              id: self.editForm.id,
              env_name: self.editForm.env_name,
              address: self.editForm.address,
              content: self.editForm.content,
            };
            //alert(params)
            let header = {
              "Content-Type": "application/json",
              Authorization:
                "Token " + JSON.parse(sessionStorage.getItem("token")),
            };
            updateEnvironment(header, params).then((_data) => {
              let { msg, code, data } = _data;
              self.editLoading = false;
              if (code === "999999") {
                self.$message({
                  message: "修改成功",
                  center: true,
                  type: "success",
                });
                self.$refs["editForm"].resetFields();
                self.editFormVisible = false;
                self.getLyzdEnterfaceList();
              } else if (code === "999997") {
                self.$message.error({
                  message: msg,
                  center: true,
                });
              } else {
                self.$message.error({
                  message: msg,
                  center: true,
                });
              }
            });
          });
        }
      });
    },
    //新增
    addSubmit: function() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          let self = this;
          this.$confirm("确认提交吗？", "提示", {}).then(() => {
            self.addLoading = true;
            //NProgress.start();
            let params = JSON.stringify({
              env_name: self.addForm.env_name,
              address: self.addForm.address,
              content: self.addForm.content,
            });

            let header = {
              "Content-Type": "application/json",
              Authorization:
                "Token " + JSON.parse(sessionStorage.getItem("token")),
            };
            addEnvironment(header, params).then((_data) => {
              let { msg, code, data } = _data;
              self.addLoading = false;
              if (code === "999999") {
                self.$message({
                  message: "添加成功",
                  center: true,
                  type: "success",
                });
                self.$refs["addForm"].resetFields();
                self.addFormVisible = false;
                self.getLyzdEnterfaceList();
              } else if (code === "999997") {
                self.$message.error({
                  message: msg,
                  center: true,
                });
              } else {
                self.$message.error({
                  message: msg,
                  center: true,
                });
                self.$refs["addForm"].resetFields();
                self.addFormVisible = false;
                self.getLyzdCaseList();
              }
            });
          });
        }
      });
    },
    selsChange: function(sels) {
      this.sels = sels;
    },

    //模板下载
    download() {
      this.templateDownload = true;
    },

    //批量删除
    batchRemove: function() {
      let ids = this.sels.map((item) => item.id);
      let self = this;
      this.$confirm("确认删除选中记录吗？", "提示", {
        type: "warning",
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        let self = this;
        let params = { ids: ids };
        let header = {
          "Content-Type": "application/json",
          Authorization: "Token " + JSON.parse(sessionStorage.getItem("token")),
        };
        delEnvironment(header, params).then((_data) => {
          let { msg, code, data } = _data;
          if (code === "999999") {
            self.$message({
              message: "删除成功",
              center: true,
              type: "success",
            });
          } else {
            self.$message.error({
              message: msg,
              center: true,
            });
          }
          self.getLyzdCaseList();
        });
      });
    },
  },
  mounted() {
    this.getProjects();
    this.getLyzdCaseList();
    this.getAPIFirstIDS();
  },
};
</script>

<style></style>
